package com.ptbuy.update;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.util.Log;

import androidx.core.content.FileProvider;


import com.ptbuy.utils.Constants;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class UpdateAppManager extends AsyncTask<String, Integer, Void> {
    // 文件分隔符
    private static final String FILE_SEPARATOR = "/";
    // 外存sdcard存放路径
    private static final String FILE_PATH = Constants.apkPath + FILE_SEPARATOR;
    // 下载应用存放全路径
    private static final String FILE_NAME = FILE_PATH + "ptbuy.apk";
    private Context context;
    // 进度条的当前刻度值
    private int curProgress;

    private ProgressDialog pd1 = null;

    public UpdateAppManager(Context context) {
        this.context = context;
    }

    /**
     * 安装新版本应用
     */
    private void installApp() {
        File appFile = new File(FILE_NAME);
        if (!appFile.exists()) {
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //判读版本是否在7.0以上
            Uri apkUri = FileProvider.getUriForFile(context, Constants.PACKAGE_NAME + ".fileprovider", appFile);//在AndroidManifest中的android:authorities值
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            install.setDataAndType(apkUri, "application/vnd.android.package-archive");
            context.startActivity(install);
        } else {
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setDataAndType(Uri.fromFile(appFile), "application/vnd.android.package-archive");
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(install);
        }

    }

    @Override
    protected Void doInBackground(String... params) {
        URL url = null;
        InputStream in = null;
        FileOutputStream out = null;
        HttpURLConnection conn = null;
        try {
            url = new URL(Constants.DOWNLOAD_URL);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(3600000);
            conn.connect();
            long fileLength = conn.getContentLength() + 2097152;//增加2M
            in = conn.getInputStream();
            File filePath = new File(FILE_PATH);
            if (!filePath.exists()) {
                filePath.mkdir();
            }

            out = new FileOutputStream(new File(FILE_NAME));
            byte[] buffer = new byte[1024];
            int len = 0;
            long readedLength = 0l;

            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
                readedLength += len;
                int tempProgress = (int) (((float) readedLength / fileLength) * 100);
                if (tempProgress - curProgress > 5) {
                    curProgress = tempProgress;
                    publishProgress(curProgress);
                }
            }
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return null;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pd1 = new ProgressDialog(Constants.CurrentContext);
        //依次设置标题,内容,是否用取消按钮关闭,是否显示进度
        pd1.setTitle("软件更新中");
        pd1.setMessage("请稍后...");
        pd1.setCancelable(false);
        pd1.setMax(100);
        pd1.setButton("取消更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                cancel(true);
                pd1.dismiss();
            }
        });
        //这里是设置进度条的风格,HORIZONTAL 是水平进度条,SPINNER 是圆形进度条
        pd1.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd1.setIndeterminate(false);
        //调用 show() 方法将 ProgressDialog 显示出来
        pd1.show();
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        pd1.dismiss();
        installApp();
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        Log.e("Constants.TAG", values[0] + "");
        if (values[0] == 100) {
            pd1.setProgress(0);
        } else {
            pd1.setProgress(values[0]);
        }
    }
}
